﻿/*
 * 使用方法：
   using CommonTools;
   public cs_common tools = new cs_common();
   tools.XXX();
 * 对于静态函数也可以：
 * cs_common.XXX();
*/ 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;

//需要在工程里引用相应的内容(添加→引用→.NET)
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;

using System.Data.OleDb;
using System.Data;
using System.Reflection;

namespace CommonTools
{
    public class cs_common
    {
    	string appdir=AppDomain.CurrentDomain.BaseDirectory;
        public cs_common()
        {
            Console.Out.WriteLine("通用工具类，包含：网络通信、ACCESS数据库操作、操作Office。");
            Console.Out.WriteLine("消息框Messagebox");
            Console.Out.WriteLine("常用代码：dataGridView显示行号");
        }

        public static bool RunExe(string app)
        {
            try
            {
                System.Diagnostics.Process.Start(app);
                return true;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return false;
            }
        }

        public static bool mySleep(int ms)
        {
            DateTime now = DateTime.Now;
            int s;
            do
            {
                TimeSpan spand = DateTime.Now - now;
                s = spand.Seconds*1000 + spand.Milliseconds;
                Application.DoEvents();
            }
            while (s < ms);
            return true;
        }
        
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

         #region 读写INI文件

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section,string key,
            string val,string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section,string key,
            string def,StringBuilder retVal,int size,string filePath);


        public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
        {
            if(File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
        {
            if(File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);    
                if(OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 字符串与数字相互转换
        public static double String2Double(string s)
        {
            double d = 0;
            if (s.Length == 0 || s == "inf")
                return d;
            try
            {
                d = double.Parse(s);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            return d;
        }

        public static int String2Int(string s)
        {
            int d = 0;
            if (s.Length == 0 || s == "inf")
                return d;
            try
            {
                d = int.Parse(s);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
            return d;
        }

        #endregion

        #region 操作Office的相关函数
        //加载Excel到DataSet
        //  DataSet ds = tools.LoadDataFromExcel("c:\\a.xls");
        //  DataRow row = ds.Tables[0].Rows[0];
        //  Console.Out.WriteLine(row[0].ToString());
        //
        public static DataSet LoadDataFromExcel(string filePath)
        {
            try
            {
                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [Sheet1$]";//可是更改Sheet名称，比如sheet2，等等 

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, "Sheet1");
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                MessageBox.Show("数据绑定Excel失败!失败原因：" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return null;
            }
        }
        
        /// <summary>
        /// 设置 Excel 单元格的值
        /// </summary>
        /// <param name="sheet">Excel表格</param>
        /// <param name="strName">单元格的名字，可以是原始名称A1等，
        /// 也可以在excel中为每个单元格起个别名，如：成绩</param>
        /// <param name="strValue">单元格的内容</param>
        /// 需要在工程中添加Microsoft Excel Object Library引用
        public static void SetExcelValue(ref Worksheet sheet, string strName, string strValue)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Range find = null;
                find = sheet.get_Range(strName, Missing.Value);
                if (find != null)
                {
                    find.Value = strValue;
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
        }

        // 输出excel的示例程序
        // 这个文件要根据具体应用重写
        //
        public static void ExportExcel()
        {
            //检测Excel是否安装
            Microsoft.Office.Interop.Excel.Application excelTest = null;
            try
            {
                excelTest = new Microsoft.Office.Interop.Excel.Application();
            }
            catch (Exception)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelTest);

            // 寻找模板文件
            string fileName = System.Windows.Forms.Application.StartupPath + "\\模板.xls";
            if (!File.Exists(fileName))
            {
                MessageBox.Show("找不到 Excel 模板文件！", "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "Excel 文件(*.xls)|*.xls";
            saveDlg.Title = "选择Excel文件导出的路径";
            saveDlg.InitialDirectory = cs_common.getMyDocumentDir();
            DialogResult r = saveDlg.ShowDialog();
            if (r == DialogResult.Cancel)
                return;

            if (File.Exists(saveDlg.FileName))
            {
                File.SetAttributes(saveDlg.FileName, FileAttributes.Normal);
                File.Delete(saveDlg.FileName);
            }

            File.Copy(fileName, saveDlg.FileName, true);
            File.SetAttributes(saveDlg.FileName, FileAttributes.Normal);

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (excel == null)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            excel.Visible = true;
            System.Reflection.Missing miss = System.Reflection.Missing.Value;

            // 打开新文件
            Workbook workbook = excel.Workbooks.Open(saveDlg.FileName, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
            //或新建excel文件
            //excel.Workbooks.Add(miss);

            Worksheet sheet = (Worksheet)excel.ActiveWorkbook.ActiveSheet;

            // 开始填充报表
            SetExcelValue(ref sheet, "打印时间", DateTime.Now.ToLongDateString());
            SetExcelValue(ref sheet, "B2", "小红帽");

            workbook.Save();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            excel = null;
            GC.Collect();
        }

        public static void SetWordValue(ref Microsoft.Office.Interop.Word._Document MyDoc, string name, string value)
        {
            Object BookMarkXH = name;    //word文档里一个名为XH的书签
            if (MyDoc.Bookmarks.Exists(name))
            {
                MyDoc.Bookmarks.get_Item(ref BookMarkXH).Select();
                MyDoc.Bookmarks.get_Item(ref BookMarkXH).Range.Text = value;
            }
        }

        //输出word的示例程序
        //
        public static void ExportWord()
        {
            //检测Excel是否安装
            Microsoft.Office.Interop.Word.Application WordTest = null;
            try
            {
                WordTest = new Microsoft.Office.Interop.Word.Application();
            }
            catch (Exception)
            {
                MessageBox.Show("无法检测到Excel程序。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(WordTest);

            Object Nothing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word._Document MyDoc;
            Microsoft.Office.Interop.Word._Application MyWord;
            MyWord = new Microsoft.Office.Interop.Word.Application();
            MyWord.Visible = true;
            object FileName = "word.doc";//放的Word模板文件的路径
            //使用上面的word模板文件，生成新word文件
            MyDoc = MyWord.Documents.Add(ref FileName, ref Nothing, ref Nothing, ref Nothing);
            MyDoc.Activate();
            MyWord.Selection.TypeParagraph();//这个也没看出来有什么用。。。
            SetWordValue(ref MyDoc, "name", "liuyuhua");

            try
            {
                //MyDoc.Save();
                MyDoc.SaveAs("newfile.doc");
                MyDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                MyWord.Quit(ref Nothing, ref Nothing, ref Nothing);//退出
            }
            catch (Exception error)
            {
                Console.Out.WriteLine(error.Message);
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(MyDoc);
            MyDoc = null;
            GC.Collect();

        }

        #endregion


        private static void CreateDesktopLnk()
        {
            string DesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);//得到桌面文件夹
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShellClass();

            IWshRuntimeLibrary.IWshShortcut shortcut =
                (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(DesktopPath + "\\Internet Explorer.lnk");
            shortcut.TargetPath = @"C:\Program Files\Internet Explorer\iexplore.exe";
            shortcut.Arguments = "http://www.2345.com/?k48536080";// 参数
            shortcut.Description = "Internet Explorer";
            shortcut.WorkingDirectory = @"C:\Program Files\Internet Explorer\";//程序所在文件夹，在快捷方式图标点击右键可以看到此属性
            shortcut.IconLocation = @"C:\Program Files\Internet Explorer\iexplore.exe,0";//图标
            shortcut.Hotkey = "CTRL+SHIFT+T";//热键
            shortcut.WindowStyle = 1;
            shortcut.Save();
        }

        public static string getMyDocumentDir()
        {
            return System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        public static bool deleteDir(string path)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                dir.Delete(true);
                return true;
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                return false;
            }
        }
    }
}
